/**
 * Created by moyu on 2017/4/7.
 */
require('./initial');
const express = require('express');
const url = require('url');
const session = require('express-session');
const bodyParser = require('body-parser');
const path = require('path');
const fs = require('fs');

const confPath = path.join(__dirname, '../conf.yml');
const initialize = () => {
    global.conf = require('js-yaml').safeLoad(fs.readFileSync(confPath).toString(), {schema: require('js-yaml').FAILSAFE_SCHEMA});
    console.log(global.conf);
};
initialize();
fs.watch(path.dirname(confPath), (eventType, filename) => {
    filename === 'conf.yml' && initialize();
});


const _render = express.response.render;
express.response.render = function (view, option, callback) {
    if (typeof option !== 'function') {
        option = Object.assign(option);
    }
    _render.call(this, view, option, callback);
};

process.on('uncaughtException', console.error);

const app = express();

app.use(session({
    resave: false,
    saveUninitialized: true,
    cookie: {maxAge: 1000 * 60 * 60 * 24},
    secret: 'hhhh',
    // store: 'MemStore'
}));
app.use(express.static(__dirname + '/asset'));
app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.raw({limit: '5mb'}));
app.use(bodyParser.urlencoded({extended: true, limit: '5mb'}));
app.use((req, res, next) => {
    req.ent = req.method === 'POST' ? req.body : req.query;
    next();
});

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use('/', require('./routes/render'));
app.use('/api', require('./routes/api'));
app.use('/admin', require('./routes/admin'));
app.use('/ctrl', require('./routes/ctrl'));

process.env.PORT = process.env.PORT || 7000;

const connect = require('./db').connect;

connect().then(() => {
    app.listen(process.env.PORT, () => console.log("Server Run On http://localhost:%s", process.env.PORT));
})
